package com.clarte.user.service;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.clarte.common.action.PagerList;
import com.clarte.common.dao.BaseDao;
import com.clarte.model.User;

@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
	@Resource(name="baseDao")
	private BaseDao<User, Integer> baseDao;
	@Override
	public void saveUser(User... user){
		for(User u : user){
			baseDao.save(u);
		}
	}

	@Override
	public void delUser(Integer... userid) {
		baseDao.delete(userid);
	}

	@Override
	public void editUser(User user) {
		baseDao.update(user);
	}

	@Override
	public User getUser(int userid) {
		return baseDao.get(userid);
	}

	@Override
	public List<User> findUser(String name, int pageNo, int rows) {
		DetachedCriteria criteria = getCriteria(name);
		List list = baseDao.findByCriteria(criteria, (pageNo-1)*rows, rows);
		int records = Long.valueOf(baseDao.getTotal(criteria.setProjection(Projections.rowCount()))).intValue();
		return PagerList.getResult(list, records);
	}

	private DetachedCriteria getCriteria(String name) {
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		if(name != null && name.trim().equalsIgnoreCase(""))
			criteria.add(Restrictions.like("name", name));
		return criteria;
	}

}
